using System.Collections.Generic;
using UnityEngine;

public class ColliderOverlapChecker:MonoBehaviour
{
    private List<Collider> m_OverlapColliders;
    public List<Collider> overlapColliders => m_OverlapColliders;

    public LayerMask checkLayerMask;
    public int overlapCollidersCount => overlapColliders.Count;

    private void Awake()
    {
        m_OverlapColliders = new List<Collider>();

        if (GetComponent<Rigidbody>() == null)
            gameObject.AddComponent<Rigidbody>().isKinematic = true;
        
    }

    private void OnTriggerEnter(Collider other)
    {
        if((LayerMask.GetMask(LayerMask.LayerToName(other.gameObject.layer)) & checkLayerMask) > 0)
        {
            if (!m_OverlapColliders.Contains(other))
            {
                m_OverlapColliders.Add(other);
            }
        }
        //GameDebug.Log($"checkLayer :{(int)checkLayer}   other ：{LayerMask.GetMask(LayerMask.LayerToName(other.gameObject.layer))} ");
    }

    private void OnTriggerExit(Collider other)
    {
        if (m_OverlapColliders.Contains(other))
        {
            m_OverlapColliders.Remove(other);
        }
    }
    private void Update()
    {
        for (int i = 0; i < m_OverlapColliders.Count;)
        {
            if (m_OverlapColliders[i])
            {
                i++;
            }
            else
            {
                m_OverlapColliders.RemoveAt(i);
            }
        }
    }
}